package com.googlecode.excavator.test.consumer;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.googlecode.excavator.consumer.ConsumerProxyFactory;
import com.googlecode.excavator.test.service.SayService;

public class ConsumerTestCase {

	private static ConsumerProxyFactory factory;
	private SayService sayService;
	
	@BeforeClass
	public static void beforeClass() throws Exception {
		factory = ConsumerProxyFactory.singleton();
	}
	
	@Before
	public void before() throws Exception {
		sayService = (SayService) factory.proxy(SayService.class, "DEFAULT", "1.0.0", 1000, null);
	}
	
	@Test
	public void test_000() {
		Assert.assertTrue(true);
	}
	
//	@Test
	public void test_001() throws Exception {
		
		Assert.assertNotNull(sayService);
		
//		System.in.read();
		
		Thread.sleep(1000);
		
		ExecutorService executor = Executors.newFixedThreadPool(50);
		long start = System.currentTimeMillis();
		final AtomicInteger successed = new AtomicInteger();
		final AtomicInteger failed = new AtomicInteger();
		final int times = 500000;
		final CountDownLatch latch = new CountDownLatch(times);
		for (int i = 0; i < times; i++) {

			executor.submit(new Runnable() {

				@Override
				public void run() {
					try {
						sayService.sayTo("dukun");
						successed.incrementAndGet();
					} catch (Exception e) {
						failed.incrementAndGet();
					} finally {
						latch.countDown();
					}
				}

			});
			
		}
		
		latch.await();
		long cost = System.currentTimeMillis() - start;
		System.out.println("cost="+cost);
		System.out.println("qps="+(times*1000/cost));
		System.out.println("fail rate="+(failed.get()*100.0/times));
		
		
		
		
	}
	
}
